#include <iostream>
#include <string>
#include <muduo/net/TcpClient.h>
#include <muduo/net/TcpConnection.h>
#include <muduo/net/Buffer.h>
#include <muduo/net/EventLoop.h>
#include <muduo/base/CountDownLatch.h>
#include <muduo/net/EventLoopThread.h>

class DictClient
{
private:
    muduo::net::EventLoopThread _loopthread; // 设置线程, 事件监控自动循环
    muduo::net::TcpConnectionPtr _conn; // 客户端本身不能发送
    muduo::CountDownLatch _downlatch; // 计数同步
    muduo::net::EventLoop* _baseloop;
    muduo::net::TcpClient _client;
private:
    // 回调方法
    void onConnectionCallback(const muduo::net::TcpConnectionPtr& conn)
    {
        if(conn->connected())
        {
            std::cout << "连接建立" << std::endl;
            _downlatch.countDown(); // 计数--, 为0唤醒
            _conn = conn;
        }
        else 
        {
            std::cout << "连接关闭" << std::endl;
            _conn.reset();
        }
    }
    void onMessageCallback(const muduo::net::TcpConnectionPtr& conn, muduo::net::Buffer* buf,
    muduo::Timestamp)
    {
        std::string msg = buf->retrieveAllAsString();
        std::cout << msg << std::endl;
    }
public:
    DictClient(const std::string sip, int sport)
    :_downlatch(1), // 初始设置为1
    _baseloop(_loopthread.startLoop()),
    _client(_baseloop, muduo::net::InetAddress(sip, sport), "DictClient")
    {
        _client.setConnectionCallback(std::bind(&DictClient::onConnectionCallback, this, std::placeholders::_1));
        _client.setMessageCallback(std::bind(&DictClient::onMessageCallback, this, 
        std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

        _client.connect(); // 连接服务器
        _downlatch.wait(); // 阻塞
    }
    bool Send(std::string& msg)
    {
        if(_conn->connected() == false) 
        {
            std::cout << "连接已经断开" << std::endl;
            return false;
        }
        _conn->send(msg);
        return true;
    }
};

int main()
{
    DictClient dc("127.0.0.1", 9090);
    while(1)
    {
        std::string str;
        std::cin >> str;
        dc.Send(str);
    }
    return 0;
}